<template>
  <div class="page">

    <!-- 体验用户到期提示 -->
    <overdue-vip ref="refOverdueVip" @event='backOpenVip'></overdue-vip>

    <!-- 页面按钮点击开通VIP弹窗 -->
    <popup ref="refOpen" @event="$refs.refOpenVip.clearCallback()">
      <open-vip ref="refOpenVip" @event="backOpenVip"></open-vip>
    </popup>

    <!-- 修改分数 -->
    <updateUser ref="refUpdateUser" @event="bindUpdata"></updateUser>

    <div class="container" v-if="data && show">
      <div class="left-wrap">
        <div class="left-wrap--box">
          <div class="info" v-if="!loading">
            <!-- userInfo为空，说明付费了，是第一次填数据 -->
            <div v-if="Object.keys(userInfo).length === 0" class="step">
              <!-- 非体验用户（付费用户）如果没有填分数信息就让他填写数据，右侧蒙版 -->
              <write-score :notProvide="notProvide" @event='bindWriteScore'></write-score>
            </div>
            <div v-if="Object.keys(userInfo).length > 0">
              <!-- 这里分为体验用户与真实用户 -->
              <div class="user-info">
                <div class="logo">
                  <img :src="userInfo.image | avatarImg(userInfo.gender)" />
                </div>
                <div class="inner">
                  <div class="name">{{realUserInfo && realUserInfo.name}}</div>
                  <div class="gender">
                    <i class="icon" :class="realUserInfo && (realUserInfo.gender?'icon-nan':'icon-nv')"></i>
                  </div>

                  <ul class="add">
                    <li v-if="province">{{province.name}}</li>
                    <li>分数:{{userInfo?userInfo.score:''}}</li>
                    <li>位次:{{userInfo?userInfo.position:''}}</li>
                    <li>{{userInfo?userInfo.scienceArt:''}}</li>
                    <li @click="bindPopup">
                      <i class="icon icon-bi" :class="!data.isEdit?'an':''"></i>
                    </li>
                    <li class="tip" v-show="userType === 1">体验账号不可修改</li>
                  </ul>

                </div>
                <div class="vip" v-if="!realUserInfo.isSuperUser">
                  <span :class="(!data.isValid || (realUserInfo.level === 'EXPERIENCE')) && 'not'"></span>
                </div>
                <div class="openVip" v-if="!realUserInfo.isSuperUser">
                  <span v-show="!data.isValid || (realUserInfo.level === 'EXPERIENCE')" @click="openVip">开通VIP</span>
                </div>
              </div>
              <div class="echarts-wrap pt20">
                <div v-show="this.aLn !== 0 && this.vLn !== 0" style="margin-left:15px; width:370px; height:200px;" id="myChart" ref="myChart"></div>
                <div v-if="ChartShow" class="chart-tip">
                  <p v-if="this.aLn === 0 || this.vLn === 0">批次线未出分，暂无法预测！</p>
                </div>
                <div v-else class="chart-tip">
                  <p>{{dataText}}</p>
                </div>
              </div>
            </div>
          </div>
          <no-content class="light" v-if="loading" :text="text"></no-content>

          <div class="tool">
            <ul>
              <li>
                <nuxt-link to="/zhiyuan/school-list">
                  <img src="/images/zhiyuan/icon1.png">
                  <div>查大学</div>
                </nuxt-link>
              </li>
              <li>
                <nuxt-link to="/zhiyuan/major-list">
                  <img src="/images/zhiyuan/icon2.png">
                  <div>查专业</div>
                </nuxt-link>
              </li>
              <li>
                <nuxt-link to="/zhiyuan/profession-list">
                  <img src="/images/zhiyuan/icon3.png">
                  <div>查职业</div>
                </nuxt-link>
              </li>
              <li>
                <!-- <nuxt-link to="/zhiyuan/holland-entry"> -->
                  <img src="/images/zhiyuan/icon4.png">
                  <div>测评选专业</div>
                <!-- </nuxt-link> -->
              </li>
            </ul>
          </div>
        </div>

      </div>
      <div class="middle-wrap">
        <div class="shadeWrap" v-if="Object.keys(userInfo).length === 0"></div>
        <!-- <div class="shadeWrap2" v-if="notProvide"></div> -->
        <zhiyuan ref="refZhiyuan"></zhiyuan>
      </div>

      <div class="right-wrap">
        <!-- <policy :province="province?province.id:''"></policy> -->
        <policy :province="realUserInfo.province?realUserInfo.province.id:''"></policy>
      </div>

    </div>
    <no-content class="light" v-else text="正在载入..."></no-content>
  </div>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/scatter'
import 'echarts/lib/component/markPoint'
import writeScore from './user/writeScore'
import overdueVip from './user/overdueVip'
import updateUser from './user/updateUser'
import zhiyuan from './index/zhiyuan'
import policy from './index/policy'
import { mapState, mapActions, mapMutations } from 'vuex'
import { formatDate, api } from '@/utils'
import openVip from '~/components/slot/openVip'
import _ from 'lodash'
// var _time = true
export default {
  layout: 'zhiyuan-new',
  data () {
    return {
      show: !1,
      text: '正在加载数据...',
      ChartShow: false,
      formatDate,
      isResult: 0,
      score: '',
      order: '',
      radio: '1',
      // 初始
      data: {},
      userInfo: {},
      interval: '',
      loading: false,
      notProvide: false,
      aLn: 0,
      vLn: 0,
      editTime: 0,
      dataText: '计算中...',
      noTips: '请保存后再查看结果'
    }
  },
  components: {
    writeScore,
    overdueVip,
    openVip,
    updateUser,
    zhiyuan,
    policy
  },
  computed: {
    ...mapState({
      firstCome: 'firstCome',
      realUserInfo: 'userInfo',
      authInfo: 'authInfo'
    }),
    userType () {
      if (this.userInfo.level === 'EXPERIENCE' && !this.userInfo.isSuperUser) {
        // 体验用户
        return 1
      } else if (this.userInfo.level !== 'EXPERIENCE' && !this.userInfo.isSuperUser) {
        // VIP用户
        return 2
      } else {
        // 超级用户
        return 3
      }
    },
    province () {
      if (Object.keys(this.userInfo).length > 0) {
        if (this.userInfo.level === 'EXPERIENCE' && !this.userInfo.isSuperUser) {
          // 体验用户取体验地址
          return this.data.province
        } else {
          // 超级用户或VIP用户取真实地址
          return this.userInfo.province
        }
      } else {
        // VIP第一次进来是没有userInfo的，所以取本地信息
        return this.realUserInfo.province
      }
    }
  },
  mounted () {
    // dom渲染完执行
  },
  created () {
    // 体验卡
    this.entryZhiyuan()
    // this.initData()
  },
  methods: {
    ...mapActions(['getUserInfo']),
    ...mapMutations(['SET_AUTH_INFO']),
    // 修改成功后后台数据来不及更新，所以延迟1S
    bindUpdata (data) {
      this.userInfo = data
      setTimeout(() => {
        this.initData()
      }, 1000)
    },
    // 开通VIP成功
    backOpenVip () {
      // this.$refs.refOpen.init(false)
      // this.$store.commit('setFirstCome', false)
      // this.initData()
      setTimeout(() => {
        location.reload()
      }, 1000)
    },
    // 首次进入未填写过分数
    bindWriteScore () {
      this.$store.commit('setFirstCome', true)
      this.initData()
    },
    // 点击修改分数
    bindPopup () {
      if (!this.data.isEdit) {
        if (!this.realUserInfo.isSuperUser) {
          if (this.realUserInfo.level === 'EXPERIENCE') {
            this.$message.warning('体验用户无法修改此数据，请开通VIP！')
          } else {
            this.$message.warning(`高考期间只能修改${this.data.editCnt}次！`)
          }
        }
      } else {
        if (this.notProvide) {
          this.$message.warning(`暂不支持该地区`)
        } else {
          this.$refs.refUpdateUser.init(this.data, this.userInfo)
        }
      }
    },
    // 点击开通VIP
    openVip () {
      this.$refs.refOpen.init() // 打开弹窗
      this.$refs.refOpenVip.init() // 加载VIP数据
    },
    initData () {
      this.$axios.get(api.getUserScore).then(data => {
        this.show = !0
        if (data) {
          this.data = data
          this.loading = false
          // 判断不支持的省份
          data.notDataProvinceIds.split(',').forEach((item) => {
            if (parseInt(item) === this.realUserInfo.province.id) {
              this.notProvide = true
            }
          })
          if (!data.userInfo) return false

          this.userInfo = data.userInfo
          if (data.userInfo.isSuperUser) {
            this.getResult(data.userInfo.score)
            return false
          }

          // if (Object.keys(data.userInfo).length > 0) {
          // if (this.realUserInfo.level === 'EXPERIENCE') {
          // 有卡并且卡失效，不是超级用户，进行弹窗提醒重新开卡
          if (this.realUserInfo.level && !data.isValid) {
            // (是否是有效用户，是否过期)体验用户过期弹窗
            // let timestamp = Date.parse(new Date())
            // if (!data.isValid && timestamp < data.endTime) this.$refs.refOverdueVip.init()
            this.$refs.refOverdueVip.init()
            console.log('VIP卡过期')
          // } else {
            // 非体验用户再次进入(vip用户)
            // this.userInfo = data.userInfo
            // this.getResult(data.userInfo.score)
          }
          data.userInfo.score && this.getResult(data.userInfo.score)
          // }

          if (this.realUserInfo.level && this.realUserInfo.level !== 'EXPERIENCE') {
            if (data.userInfo) {
              let authInfo = this.lodash.cloneDeep(this.authInfo)
              authInfo.isValid = true
              authInfo.level = this.userInfo.level
              this.SET_AUTH_INFO(authInfo)
              this.getUserInfo(this)
              console.log('authInfo', this.authInfo)
            } else {
              this.$store.commit('setFirstCome', false)
            }
          }
        } else {
          // 用户过期
          if (!data.isValid) {
            this.$nextTick(function () {
              this.$refs.refOverdueVip.init()
              console.log('体验卡过期')
            })
          }
        }
      }).catch(data => {
        this.text = '网络走丢了，请稍后重试！'
        this.noTips = '网络走丢了，请稍后重试！'
      })
    },
    entryZhiyuan () {
      if (!this.realUserInfo.level) {
        this.$axios.post(api.tiralBinding, { phoneNumber: this.realUserInfo.phoneNumber }).then(data => {
          const copyUserInfo = _.clone(this.realUserInfo)
          copyUserInfo.level = 'EXPERIENCE'
          copyUserInfo.isValid = true
          this.$store.commit('SET_USER_INFO', copyUserInfo)

          let authInfo = this.lodash.cloneDeep(this.authInfo)
          authInfo.isValid = true
          authInfo.level = 'EXPERIENCE'
          this.SET_AUTH_INFO(authInfo)

          this.getUserInfo(this)
          this.$message.success('恭喜您获得3天志愿卡专属功能体验期，体验期后可在会员中心购买志愿卡')

          this.initData()
          console.log('开通体验卡')
        }).catch(err => {
          if (err.code === 2) {
            // 您已经体验过本产品,请勿重复体验
          }
        })
      } else {
        // 志愿卡/全能卡/体验卡
        // if(level==='ZHI_YUAN'||level==='FULL_FEATURED'||level==='EXPERIENCE')
        this.initData()
        console.log('存在VIP卡')
      }
    },
    getResult (score) {
      this.$axios.get(api.getStatistics).then(data => {
        console.log('您的位置曲线图', data)
        if (data) {
          // data.across = []
          // data.vertical = []
          // data.across = data.across.reverse()
          // data.across[0].batchName = '本科一批'
          // data.across[1].batchName = '本科二批'
          // data.across[2].batchName = '本科批'
          // data.across[3].batchName = '本科A段'
          // console.log('data.acros', data.across[0])
          this.ChartShow = true
          this.vLn = data.vertical.length
          this.aLn = data.across.length

          // 大学填报数量
          this.$refs.refZhiyuan.init(data.canCount)

          // this.staticData = data
          let cateDataTop = []
          if (data.across) {
            data.across.forEach(item => {
              cateDataTop.push(item.scoreLine)
            })
          }
          const { minScore, maxScore, modeScore } = data.vertical[0]
          cateDataTop = [...cateDataTop, minScore, maxScore, modeScore, score]
          cateDataTop.sort(function (a, b) {
            return b - a
          })
          /* 去重 */
          cateDataTop = _.sortedUniq(cateDataTop)
          let cateDataBottom = []
          for (let i = 0; i < cateDataTop.length; i++) {
            let item = cateDataTop[i]
            cateDataBottom[i] = '\n'
            data.across.forEach(ceil => {
              if (item === ceil.scoreLine) {
                let str
                // if (ceil.batchName.indexOf('本') > -1) {
                if ((ceil.batchName.length > 3 && ceil.batchName.indexOf('本科') > -1 && ceil.batchName.indexOf('段') < 0) || (ceil.batchName.length > 4 && ceil.batchName.indexOf('段') > -1)) {
                  str = ceil.batchName.substr(2, ceil.batchName.length - 1) + '\n' + ceil.scoreLine
                } else {
                  str = ceil.batchName + '\n' + ceil.scoreLine
                }
                cateDataBottom[i] = str
                // }
              }
            })
          }
          let seriesData = cateDataTop.map(function (item) {
            if (item !== modeScore) {
              return -item
            } else {
              return item
            }
          })
          cateDataTop = cateDataTop.reverse()
          seriesData = seriesData.reverse()
          cateDataBottom = cateDataBottom.reverse()
          seriesData[0] = seriesData[seriesData.length - 1]
          seriesData[1] = seriesData[seriesData.length - 1] - 20
          /* 获取我的索引 */
          const myPositionIndex = _.findIndex(cateDataTop, function (item) {
            return score === item
          })
          // console.log(cateDataTop)
          console.log('中间', seriesData)
          // console.log(cateDataBottom)
          let option = {
            xAxis: [{
              type: 'category',
              // 去首尾空隙
              boundaryGap: false,
              // data: ['一本520', '二本440', '三本300', '专科200'],
              data: cateDataBottom,
              //  interval: 1,
              axisLine: {
                onZero: false,
                // X轴的颜色
                lineStyle: {
                  color: 'rgba(255,255,255,.5)'
                }
              },
              axisTick: {
                // 去除刻度
                show: false
                // length: 20
              },
              axisLabel: {
                // 表示每间隔0个点显示一个标签
                interval: 0,
                show: true,
                // 设置X轴字体颜色
                textStyle: {
                  color: '#fff'
                }
              },
              splitLine: {
                // 显示网格线
                show: true,
                lineStyle: {
                  color: 'rgba(255,255,255,.5)',
                  type: 'dotted'
                }
              }
            }, {
              type: 'category',
              boundaryGap: false,
              show: false,
              data: cateDataTop
            }],
            yAxis: {
              // 去首尾空隙
              type: 'value',
              // 不显示Y轴
              show: false
            },
            // 整个图的位置（其实是设置大小）
            grid: {
              left: 15,
              right: 15,
              top: 30,
              bottom: 40
              // containLabel: true
            },
            series: [{
              data: seriesData,
              // [-101, -200, -400, -409, -450, 472, -513, -702]
              // data: [-702, -700, -400, -409, -450, 472, -513, -702],
              // data: vertical,
              type: 'line',
              smooth: true,
              xAxisIndex: 1,
              // 设置拐点为实心圆
              symbol: 'circle',
              // 拐点圆的大小
              symbolSize: 8,
              itemStyle: {
                normal: {
                  // 拐点颜色
                  color: '#4BB8EE',
                  borderColor: '#fff'
                }
              },
              // 折线粗细，阴影
              lineStyle: {
                normal: {
                  color: '#fff',
                  width: 2,
                  shadowColor: '#fff',
                  shadowBlur: 40,
                  shadowOffsetY: 15
                }
              },
              // 不显示节点
              showSymbol: false
            }, {
              symbolSize: 8,
              xAxisIndex: 1,
              type: 'scatter',
              label: {
                show: true,
                position: (function () {
                  if (myPositionIndex === 0) {
                    return [0, -30]
                  } else if (myPositionIndex === cateDataTop.length - 1) {
                    return [-60, -30]
                  } else {
                    return [-27, -30]
                  }
                })(),
                fontSize: 13,
                padding: [5, 8],
                shadowColor: 'rgba(255,255,255,0.5)',
                formatter: '您的位置',
                shadowBlur: 8,
                borderRadius: 14,
                backgroundColor: '#fff'
              },
              itemStyle: {
                color: '#4BB8EE',
                borederWidth: 2,
                borderColor: '#fff'
              },
              data: [[myPositionIndex, seriesData[myPositionIndex]]]
            }]
          }
          let chartInstance = echarts.init(this.$refs.myChart)
          chartInstance.setOption(option)
        }
      }).catch(err => {
        console.log(err)
        this.dataText = '网络走丢了，请稍后重试！'
        this.noTips = '网络走丢了，请稍后重试！'
      })
    },
    edit () {
      if (!this.data.isEdit) {
        if (this.realUserInfo.level === 'EXPERIENCE') {
          this.$toast('体验用户无法修改此数据，请开通VIP！')
        } else {
          this.$toast(`高考期间只能修改${this.data.editCnt}次！`)
        }
      } else {
        this.editTime++
        this.isResult = false
        // this.staticData = {}
        // this.count = {}
      }
    }
  },
  beforeMount () {
  }
}
</script>

<style lang="scss" scoped>
$radius: 12px;
.chart-tip{
  text-align: center;
  color:#FFF;
  &p{
    padding:50px 0;
  }
}
.page {
  min-height: 100%;
  height: auto;
  padding-bottom: 44px\9;
  background-color: #fafafa;
  .container {
    display: flex;
    justify-content: center;
    // padding: 0 60px;
    // min-width: 1440px;
    .left-wrap,
    .right-wrap,
    .middle-wrap {
      border-radius:15px;
      .bg{
        background-color: $light;
      }
      /deep/ .tab_bubble {
        padding: 15px 20px;
        border-bottom:1px solid #F3F3F3;
        .title{
          font-size:24px;
          height:33px; line-height:33px;
          font-weight:normal;
          color:#1D1E2C;
        }
        .more{
          margin-left: auto;
          font-size:14px;
          color: $positive;
          cursor:pointer;
        }
      }
      .top {
        display: flex;
        flex-direction: column;
        height: 350px;
        position: relative;
        &::after {
          content: "";
          border-bottom: 1px solid #ececec;
          position: absolute;
          bottom: 17px;
          height: 2px;
          left: 0;
          right: 0;
        }
        // .searchHeader {
        //   margin-top: 40px;
        //   font-size: 24px;
        //   text-align: center;
        // }
      }
    }
    .left-wrap {
      // width: 430px;
      width: 400px;
      .left-wrap--box{
        // background:$light;
        border-radius:$radius;
        .info{
          position:relative;
          height:369px;
          // background:$light;
          // background:$positive;
          border-radius:$radius;
          background: linear-gradient(180deg, #82DDF8 0%, #4BB8EE 100%) !important;
          .user-info{
            display: flex;
            align-items:center;
            .logo{
              width:102px; padding:15px;
              font-size:0px;
              img{
                width:72px; height:72px;
                border-radius:72px;
              }
            }
            .inner{
              position:relative; z-index:2;
              width:100%;
              display: flex;
              flex-direction: column;
              .name{
                height:25px; line-height:25px;
                color:#FFF;
              }
              .gender{
                height:26px; line-height:26px;
                font-weight:bold;
                .icon-nan{
                  // color:$table-b;
                  color:#FFF;
                }
                .icon-nv{
                  // color:#FF5089;
                  color:#FFF;
                }
              }
              .add{
                position:relative;
                display: flex;
                height:20px; line-height:20px;
                color:#FFF;
                font-size:14px;
                justify-content: space-between;
                li{
                  position: relative;
                  padding-right:5px;
                  &.maxw{max-width:100px;}

                  &.tip{
                    position:absolute; left:0px; top:20px;
                    color:$pink;
                    font-size:10px;
                  }
                  &.update{
                    display:flex;
                    >span{
                      flex:1; overflow:hidden;
                      input{
                        position: relative; z-index:2;
                        width:50px;
                        border:none;
                        background:transparent;
                      }
                      &::before{
                        position: absolute; right: 10px; top: 0px;
                        font-family: "iconfont" !important;
                        font-size: $size16;
                        font-style: normal;
                        -webkit-font-smoothing: antialiased;
                        -moz-osx-font-smoothing: grayscale;
                        content: "\e6bc";
                      }
                    }

                  }
                  .el-dropdown-link{
                    display:inline-block;
                    width:50px;
                    cursor:pointer;
                  }
                }
                i{
                  font-size:14px;
                  margin-left:5px;
                  width:30px; text-align:center; cursor:pointer
                }
              }
            }
            .vip{
              position:absolute; top:0; right:0; z-index:1;
              width:258px; height:100px;
              >span{
                display: block; width:100%; height:100%;
                background:url('/images/zhiyuan/shape.png') no-repeat center center;
                background-size: cover;
                &.not{
                  background:url('/images/zhiyuan/not.png') no-repeat center center;
                }
              }
            }
            .openVip{
              position: absolute; right: 20px; top: 20px; z-index:3;
              >span{
                display: block;
                height: 32px; line-height:32px;
                width: 82px; text-align: center;
                background: $pink;
                border-radius: 20px;
                font-size:16px;
                color:$light;
                cursor: pointer;
              }
            }
          }
        }
        .tool{
          margin-top: 15px;
          background: $light;
          border-radius:12px;
          padding:15px 22px;
          ul{
            display:flex;
            justify-content: space-between;
            color:#69707F;
            font-size:14px;
            line-height:20px;
            text-align:center;
            img{
              font-size:0;
            }
          }
        }
      }
    }

    .middle-wrap {
      position:relative;
      width: 400px;
      display: flex;
      flex-direction: column;
      margin: 0 15px;
      .shadeWrap{
        // filter:blur(2px);
        position:absolute; left:0; top:0px; z-index:10;
        width:100%; height:100%;
        border-radius:12px;
        background:rgba(255,255,255,0.9);
        color:$stable-ad;
        display:flex;
        align-items: center;
        &:after{
          width:100%; text-align:center;
          height:33px; line-height:33px;
          font-size:24px;
          display: block;
          content:"- 请先填写左侧信息 -";
        }
      }
      .shadeWrap2{
        // filter:blur(2px);
        position:absolute; left:0; top:0px; z-index:10;
        width:100%; height:100%;
        border-radius:12px;
        background:rgba(255,255,255,0.9);
        color:$stable-ad;
        display:flex;
        align-items: center;
        &:after{
          width:100%; text-align:center;
          height:33px; line-height:33px;
          font-size:24px;
          display: block;
          content:"- 暂不支持该地区 -";
        }
      }
    }
    .right-wrap {
      // flex: 1;
      width: 415px;
    }
  }
}
@media screen and(-ms-high-contrast:active), (-ms-high-contrast: none) {
  .page {
    padding-bottom: 44px;
  }
}
</style>
